package triannon.client.sprites;

import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;

import org.jdom.Element;

import triannon.client.util.ResourceLocator;
import triannon.client.util.XMLIO;

public class SpriteInfoMap {
	private final HashMap<String, SpriteInfo> map = new HashMap<String, SpriteInfo>();

	private static SpriteInfoMap instance = null;

	private SpriteInfoMap() {
		// TRY TO PARSE XML FILES FOR ALL AVAILABLE SPRITE TYPES
		for (SpriteType spriteType : SpriteType.values()) {
			URL url = ResourceLocator.getResource(spriteType.toString().toLowerCase()
					+ ".xml");
			if (url != null) {
				put(spriteType, url);
			} else {
				System.err.println("File " + spriteType.toString().toLowerCase()
						+ ".xml" + " not found");
			}
		}

	}

	private void put(SpriteType spriteType, URL url) {
		Element element = XMLIO.readXML(url);
		Iterator<?> it = element.getChildren("sprite").iterator();

		while (it.hasNext()) {
			Element spriteElem = (Element) it.next();
			SpriteInfo info = new SpriteInfo(spriteType, spriteElem);
			map.put(info.getKey(), info);
		}
	}

	public static SpriteInfoMap getInstance() {
		if (instance == null) {
			instance = new SpriteInfoMap();
		}

		return instance;
	}

	public SpriteInfo get(String key) {
		SpriteInfo info = map.get(key);
		if (info == null) {
			System.err.println("Sprite " + key + " does not exist");
		}
		return info;
	}

	public static void main(String[] args) {
		ResourceLocator.addResourceDir("triannon/client/resource/sprites/");
		SpriteInfoMap simap = SpriteInfoMap.getInstance();
		System.err.println(simap.map);
	}
}
